<template>
  <el-popover
    :placement="placement"
    :width="style.width"
    trigger="click"
    content="这是一段内容,这是一段内容,这是一段内容,这是一段内容。"
    :show-arrow="false"
  >
    <template #reference>
      <el-input
        v-model="selectValue"
        placeholder="请输入内容"
        :style="style"
        readonly
      ></el-input>
    </template>
    <el-tree
      :data="options"
      :props="props"
      @node-click="nodeClick"
      :expand-on-click-node="clickExpand"
    ></el-tree>
  </el-popover>
</template>

<script>
export default {
  name: 'SelectTree',
  props: {
    change: {
      type: Function,
    },
    model: {
      type: String,
    },
    treeVal:{
      type: String
    },
    options: {
      type: Array,
    },
    props: {
      type: Object,
      default: function () {
        return {
          children: 'children',
          label: 'label',
        };
      },
    },
    style: {
      props: Object,
    },
    placement: {
      type: String,
      default: 'bottom',
    },
  },

  data() {
    return {
      selectValue: '',
      clickExpand: false,
    };
  },
  methods: {
    nodeClick(val) {
      this.selectValue = val.name;
      this.$emit('update:treeVal', val.id);
      this.change(val.id);
    },
    findNodeFromTree(tree, id) {
      for (let i = 0, l = tree.length; i < l; i++) {
        if (tree[i].id === id) {
          return tree[i];
        } else {
          const rst = this.findNodeFromTree(tree[i].children, id);
          if (rst) {
            return rst;
          }
        }
      }
      return null;
    },
  },
  watch: {
    options: function (val) {
      if (this.model && val) {
        const node = this.findNodeFromTree(this.options, this.model);
        this.selectValue = node.name;
      }
    },
    model: function (val) {
      if (val) {
        const node = this.findNodeFromTree(this.options, val);
        this.selectValue = node.name;
      }
    },
    treeVal: function(val){
      if (val) {
        const node = this.findNodeFromTree(this.options, val);
        this.selectValue = node.name;
      }
    }
  },
};
</script>

<style scoped>
</style>
